package appTool

import (
	"fmt"
	"gitee.com/kinwyb/appTools/common"
	"gitee.com/kinwyb/appTools/log"
	"io"
	"strings"
)

// 应用追踪
type appTrace struct {
	cfg             *appCfg   `description:"配置信息"`
	tracingReporter io.Closer `description:"追踪对象"`
}

// 初始化追踪系统
func (a *appTrace) initTracing() {
	if a.cfg.tracerServerURL == "" {
		common.Tracing = false
		return
	}
	common.Tracing = a.cfg.tracerServerURL != ""
	if common.Tracing {
		if strings.HasPrefix(a.cfg.tracerServerURL, "zipkin@") {
			log.AppTool.Infof("zipkin追踪服务开启：%s", a.cfg.tracerServerURL)
			var addr string
			if a.cfg.httpAddr != "" {
				addr = fmt.Sprintf("%s:%d", a.cfg.httpAddr, a.cfg.httpPort)
			} else {
				addr = common.LocalIPv4()
			}
			zipkinURL := strings.TrimPrefix(a.cfg.tracerServerURL, "zipkin@")
			a.tracingReporter = common.StartZipkinServer(
				zipkinURL,
				addr,
				a.cfg.appName)
		} else if strings.HasPrefix(a.cfg.tracerServerURL, "apm@") {
			log.AppTool.Infof("apm追踪服务开启：%s", a.cfg.tracerServerURL)
			apmURL := strings.TrimPrefix(a.cfg.tracerServerURL, "apm@")
			a.tracingReporter = common.StartElasticAPMServer(
				apmURL,
				a.cfg.cfg.RunMode().String(),
				a.cfg.appName)
		} else {
			log.AppTool.Warnf("未知的追踪服务：%s", a.cfg.tracerServerURL)
		}
		common.Tracing = a.tracingReporter != nil
	}
}

// 关闭追踪
func (a *appTrace) closeTracing() {
	if a.tracingReporter != nil {
		a.tracingReporter.Close()
		a.tracingReporter = nil
		common.Tracing = false
	}
}
